package com.neeraj.SharingArtifacts;

import java.io.File;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class ShowArtifactsTabs extends TabActivity {
		
	private static final String DEBUG_TAG = "SHOW ARTIFACTS TABS";
	private static Handler response = null;
	boolean isUploaded =false;
	boolean isThreadAlive = false;
	Button upload;
	TabHost tabHost;
	DatabaseHelper dbHelper;
	ProgressDialog progressDialog;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_artifact_tab_view);
        
        tabHost = getTabHost();
        
        // Tab for All Artifacts Together
//        TabSpec allspec = tabHost.newTabSpec("All");
//        allspec.setIndicator("All", getResources().getDrawable(R.drawable.icon_photos_tab));
//        Intent allIntent = new Intent(this, AllArtifactsTab.class);
//        allspec.setContent(allIntent);
        
        // Tab for Images
        TabSpec imagespec = tabHost.newTabSpec("Images");
        imagespec.setIndicator("Images", getResources().getDrawable(R.drawable.icon_photos_tab));
        Intent imagesIntent = new Intent(this, ImagesTab.class);
        imagespec.setContent(imagesIntent);
              
        // Tab for Videos
        TabSpec videospec = tabHost.newTabSpec("Videos");
        videospec.setIndicator("Videos", getResources().getDrawable(R.drawable.icon_videos_tab));
        Intent videosIntent = new Intent(this, VideoTab.class);
        videospec.setContent(videosIntent);
        
        // Tab for Audio
        TabSpec audiospec = tabHost.newTabSpec("Audio");
        // setting Title and Icon for the Tab
        audiospec.setIndicator("Audio", getResources().getDrawable(R.drawable.icon_songs_tab));
        Intent audioIntent = new Intent(this, AudioTab.class);
        audiospec.setContent(audioIntent);
        
     // Tab for Text
        TabSpec textspec = tabHost.newTabSpec("Text");
        // setting Title and Icon for the Tab
        textspec.setIndicator("Text", getResources().getDrawable(R.drawable.icon_songs_tab));
        Intent textIntent = new Intent(this, TextTab.class);
        textspec.setContent(textIntent);
        
        // Adding all TabSpec to TabHost
//        tabHost.addTab(allspec); // Adding all tab
        tabHost.addTab(imagespec); // Adding photos tab
        tabHost.addTab(audiospec); // Adding songs tab
        tabHost.addTab(videospec); // Adding videos tab
        tabHost.addTab(textspec); // Adding text tab
        
        upload = (Button) findViewById(R.id.buttonUpload);
//        delete = (Button) findViewById(R.id.buttonDelete);
        
        upload.setOnClickListener(actionButtonOnClickListener);
//        delete.setOnClickListener(actionButtonOnClickListener);
    }
    
    @Override
	public void onStart()
	{
		try {
			super.onStart();
			dbHelper=new DatabaseHelper(this);
			dbHelper.insertTypeData();
		} catch(Exception ex) {			
			CatchError(ex.toString());
		}
	}
    
    Button.OnClickListener actionButtonOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			if(v.getId()==R.id.buttonUpload){
				ArrayList<String> ar = null;
//				if(tabHost.getCurrentTabTag().equals("All")){
//					ar = AllArtifactsTab.getInstance().checkedAllItems;					
//				}
//				else 
					if(tabHost.getCurrentTabTag().equals("Images")){
					ar = ImagesTab.getInstance().checkedImageItems;					
				}
				else if(tabHost.getCurrentTabTag().equals("Audio")){
					ar = AudioTab.getInstance().checkedAudioItems;
					
				}
				else if(tabHost.getCurrentTabTag().equals("Videos")){
					ar = VideoTab.getInstance().checkedVideoItems;					
				}
				else {
					ar = TextTab.getInstance().checkedTextItems;					
				}
				Log.i(DEBUG_TAG, "10. "+ar.toString());
				final ArtifactAttributes[] art = dbHelper.getArtifacts(ar, getApplicationContext());
				callUploadData(art);				
			}
		}
    	
    };
    
    @SuppressLint("HandlerLeak")
	void callUploadData(final ArtifactAttributes[] art) {
    	Thread thread=null;
    	for (final ArtifactAttributes artifactAttributes : art) {
			Log.i(DEBUG_TAG, "15. "+artifactAttributes.getLatitude());
			Log.i(DEBUG_TAG, "16. "+artifactAttributes.getLongitude());
			Log.i(DEBUG_TAG, "17. "+artifactAttributes.getAltitude());
			Log.i(DEBUG_TAG, "18. "+artifactAttributes.getUtcTime());
			Log.i(DEBUG_TAG, "19. "+artifactAttributes.getDate());
			Log.i(DEBUG_TAG, "20. "+artifactAttributes.getContent());
			Log.i(DEBUG_TAG, "21. "+artifactAttributes.getContent_file_name());
			Log.i(DEBUG_TAG, "22. "+artifactAttributes.getArtifactType());
			
			final UploadData upload = new UploadData();
			
			progressDialog = ProgressDialog.show(this, "", "Uploading files to server.....", false);			
			thread=new Thread(new Runnable(){
                   public void run(){
                	   isThreadAlive = true;
                	   isUploaded = upload.doFileUpload1(artifactAttributes.getContent(), artifactAttributes);
                	   if(isUploaded) {
                		   Log.i(DEBUG_TAG, "23. isUpload " + isUploaded);
                		   dbHelper.updateIsUpload(artifactAttributes.getContent_file_name());
                		   progressDialog.setTitle("Uploading Finished!");
                	   } else {
                		   progressDialog.setTitle("Uploading Failed!");
                	   }
                	   runOnUiThread(new Runnable(){
                           public void run() {
                               if(progressDialog.isShowing()) {                            
                            	   progressDialog.dismiss();                            	
                            	   isThreadAlive = false;
                               }                                  
                           }
                       });
                	   response.sendEmptyMessage(0);
                   }
           });
	       thread.start();	 
	       
	       response = new Handler() {
	    		public void handleMessage(Message msg) {
	                super.handleMessage(msg);
	                try {
	                	if(isUploaded){
	        				Toast.makeText(getApplicationContext(), "Upload Successful", Toast.LENGTH_LONG).show();
	        				ArrayAdapter<String> adapter = null;
	        				
//	        				if(tabHost.getCurrentTabTag().equals("All")){
//	        					adapter = AllArtifactsTab.getInstance().fileList;					
//	        				}
//	        				else 
	        					if(tabHost.getCurrentTabTag().equals("Images")){
	        					adapter = ImagesTab.getInstance().fileList;					
	        				}
	        				else if(tabHost.getCurrentTabTag().equals("Audio")){
	        					adapter = AudioTab.getInstance().fileList;
	        					
	        				}
	        				else if(tabHost.getCurrentTabTag().equals("Videos")){
	        					adapter = VideoTab.getInstance().fileList;					
	        				}
	        				else {
	        					adapter = TextTab.getInstance().fileList;					
	        				}
	        				adapter.remove(artifactAttributes.getContent_file_name());
	        				adapter.notifyDataSetChanged();	        				
	        				if(!artifactAttributes.getArtifactType().equals("text")) {
	        					File file=null;
		        				File mediaStorageDir=null;
	        					String filename = artifactAttributes.getContent_file_name();
	        					
	        					if(artifactAttributes.getArtifactType().equals("image")){
	        						mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	        					              Environment.DIRECTORY_DCIM), "SharingArtifacts/image");
	        					}
	        					else if(artifactAttributes.getArtifactType().equals("audio")) {
	        						mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	        					              Environment.DIRECTORY_DCIM), "SharingArtifacts/audio");
	        					}
	        					else if(artifactAttributes.getArtifactType().equals("video")) {
	        						mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	        					              Environment.DIRECTORY_DCIM), "SharingArtifacts/video");
	        					}
	        					file = new File(mediaStorageDir.getPath() + File.separator + filename);
	        					boolean isFileDel = file.delete();
		        				Log.i(DEBUG_TAG, "file deletion status:"+ isFileDel);
	        				}					        				
	        			}
	                } 
	                catch (Exception e) {
	                    e.printStackTrace();
	                }                       
	            }
	    	};
		}    	
    }

    void CatchError(String Exception) {	    	
    	Dialog diag=new Dialog(this);
    	diag.setTitle("Error!!!");
    	TextView txt=new TextView(this);
    	txt.setText(Exception);
    	diag.setContentView(txt);
    	diag.show();
    }
}
